

#include <KF8TS2716.h>
#include "jxos_public.h"
#include "driver/74hc595.h"
#include "state.h"
#include "uart_rec.h"

/*******************************************/
static uint16_t c_10;
static uint16_t c_2_5;
static uint16_t c_1;
static uint16_t d_10um;
static uint16_t d_5um;
static uint16_t d_5um;
static uint16_t d_2_5um;
static uint16_t d_1um;
static uint16_t d_0_5um;
static uint16_t d_0_3um;

static uint16_t uint8_Merge_uint16(uint8_t H, uint8_t L)
{
    uint16_t  uMerge = 0;
    uMerge = H;
    uMerge <<= 8;
    uMerge += L;
    return uMerge;
}

static void valueInit()
{
    c_10 = 0;
    c_2_5 = 0;
    c_1 = 0;

    d_0_3um = 0;
    d_0_5um = 0;
    d_1um = 0;
    d_2_5um = 0;
    d_5um = 0;
    d_10um = 0;

}

static void setValue(unsigned char d[])
{
    c_10 = uint8_Merge_uint16(d[4],d[5]);
    c_2_5 = uint8_Merge_uint16(d[6],d[7]);
    c_1 =  uint8_Merge_uint16(d[8],d[9]);

    d_0_3um = uint8_Merge_uint16(d[10],d[11]);
    d_0_5um =  uint8_Merge_uint16(d[12],d[13]);
    d_1um =  uint8_Merge_uint16(d[14],d[15]);
    d_2_5um =  uint8_Merge_uint16(d[16],d[17]);
    d_5um =  uint8_Merge_uint16(d[18],d[19]);
    d_10um =  uint8_Merge_uint16(d[20],d[21]);
}

/*******************************************/
static swtime_type led_swt;
static swtime_type second_swt;
static uint8_t led_show = 0XFF;
static uint8_t led_show_flag = 0;
void tick_handler_task(void)
{
	if(sys_svc_software_timer_check_overtime(led_swt) == 1){
		if(led_show_flag == 0){
			hc_74hc595_output(~led_show);
		}
		else{
			hc_74hc595_output(led_show);
		}
		led_show <<= 1;
		if(led_show == 0){
			led_show = 0xff;
			led_show_flag = !led_show_flag;
		}	
	}

	if(sys_svc_software_timer_check_overtime(second_swt) == 1){
		state_second_tick_event_handler();
	}

	if(uart_rec_finish_flag == 1){
		setValue(uart_frame_buffer);
		uart_rec_finish_flag = 0;
		state_pm25_data_rec_event_handler(c_2_5);
	}	
}

void tick_handler_task_init(void)
{	
	TR23 = 0;	//74CH595 SI
	TR24 = 0;	//74CH595 RCK
	TR25 = 0;	//74CH595 SCK
	hc_74hc595_output(0);

	led_swt = sys_svc_software_timer_new();
	sys_svc_software_timer_set_time(led_swt, 100);
	sys_svc_software_timer_restart(led_swt);

	second_swt = sys_svc_software_timer_new();
	sys_svc_software_timer_set_time(second_swt, 1000);
	sys_svc_software_timer_restart(second_swt);

	valueInit();

	state_init();
}

/*******************************************/
void led_set_speed(uint16_t ms)
{
	sys_svc_software_timer_set_time(led_swt, ms);
}
